class Teaching < ActiveRecord::Base
  # Relations
  belongs_to  :user
  belongs_to  :project
  has_many    :deadlines,
              :dependent => :destroy
  has_many    :groups,
              :dependent => :destroy
  
  # Validations
  validate                :check_subsequent_dates
  validates_presence_of   :user_id, :project_id, :start, :end
  validates_not_zero      :user_id, :project_id
  validates_uniqueness_of :user_id,
                          :scope => :project_id
  
  # Checks that end is after start
  #
  def check_subsequent_dates
    if self.end <= self.start
      self.errors.add(:end, 'should come after start')
      return false
    end
    return true
  rescue
    return false
  end
  
  # Returns title for teaching. It concats the project's title with the teacher's name
  #
  def title
    "#{self.project.title} - #{self.user.name}"
  end
  
  # If the user is following the class, it returns the group she belongs to,
  # otherwise false is returned
  #
  def is_member?(user)
    user = User.find(user) unless user.is_a?(User)
    return false if user.is_teacher?
    group = self.groups.find(:first, :conditions => ['users.id = ?', user.id], :include => :users)
    return group.nil? ? false : group
  end
  
  # Returns wether or not the teaching is old
  #
  def is_old?
    self.end.to_time.tomorrow < Time.now
  end
end
